package com.core.netty.http;

import com.core.netty.http.Intercept.MyInterceptFactory;
import com.core.netty.http.work.SerlvetUtil;
import com.core.safe.SafeCache;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HttpServer {
    private volatile List<String> classNames = new ArrayList<>();

    public HttpServer(int port) {
        //初始化serlvet
        initSerlvet();
        //初始化拦截器
        MyInterceptFactory.init();
        //初始化mysql连接池
        //SqlHelper.init();
        //初始化安全框架mysafe
        SafeCache.init();
        //启动服务
        bind(port);


    }

    private void bind(int port) {
        long start = new Date().getTime();

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024); // 连接数
            //bootstrap.option(ChannelOption.TCP_NODELAY, true); // 不延迟，消息立即发送
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 长连接
            bootstrap.childHandler(new HttpIniter());
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            if (channelFuture.isSuccess()) {
                long end = new Date().getTime();
                System.err.println("启动所需时长:" + (end - start) + "ms");
                System.err.println("启动Netty服务成功，端口号：" + port);
            }
            // 关闭连接
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            System.err.println("启动Netty服务异常，异常信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    private void initSerlvet() {
        SerlvetUtil.init();
        SerlvetUtil.initSerlvet();
    }

    public static void main(String[] args) throws InterruptedException {
        new HttpServer(8897);
    }

}
